import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Router } from '@angular/router';
import 'rxjs/add/operator/toPromise';
import { UtilsService } from './utils/utils.service';
import { AuthTokenService }  from './authToken.service';
import { Observable } from 'rxjs/Observable';

@Injectable()

export class ActionService {

      constructor(
            private http: Http,
            private utils: UtilsService,
            private authToken:AuthTokenService
      ) { }

      //http->token-psot
      post(url:string,data?:any){

            let authToken = this.authToken.getToken();
            let token = authToken.token_type+' '+authToken.access_token;

            let headers = new Headers({ 'Content-Type': 'application/json', "Authorization": token});
            
            return this.http.post(url, data, { headers: headers })
                  .map(this.extractData)
                  .catch(error => {

                        if (error.status == 401) {
                              alert('身份验证错误！')
                              //报401 身份错误 清空本地缓存和内存的数据 跳登录界面重新登录
                              this.authToken.logout();
                              //todo  将当前路由地址传给auth.service
                        } else if(error.status == 400){
                              alert('请求参数错误！');
                        }else{
                              alert('系统异常,请稍后重试！');
                        }

                        //异常信息返回
                        const err = error || JSON.stringify(error);
                        let errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
                        return Observable.throw(errMsg);
                  });
      }
      
      postForm(url:string,data?:any){

            let authToken = this.authToken.getToken();
            let token = authToken.access_token;

            let oUrl =url+"?access_token=" + token; 
            
            return this.http.post(oUrl, data)
                  .map(this.extractData)
                  .catch(error => {

                        if (error.status == 401) {
                              //报401 身份错误 清空本地缓存和内存的数据 跳登录界面重新登录
                              this.authToken.logout();
                              //todo  将当前路由地址传给auth.service
                        }

                        //异常信息返回
                        const err = error || JSON.stringify(error);
                        let errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
                        console.log(errMsg);
                        return Observable.throw(errMsg);
                  });
      }

      //成功
      private extractData(res: Response) {
            let body = res.json();
            return body.data || body;
      }


}